using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[DisallowMultipleComponent]
public abstract class Entity : MonoBehaviour
{
    public EntityData EntityData;
    
    // 组件缓存 - 按需获取，不强求存在
    private Dictionary<System.Type, Component> m_ComponentCache = new Dictionary<System.Type, Component>();
    
    // 基础属性
    public Animator Animator { get; private set; }

    /// <summary>
    /// 是否处于隐身状态
    /// </summary>
    public bool IsStealth { get; private set; }

    /// <summary>
    /// 是否处于无敌状态
    /// </summary>
    public bool IsInvincible 
    { 
        get 
        { 
            var health = GetEntityComponent<HealthComponent>();
            return health?.IsInvincible ?? false;
        } 
    }

    /// <summary>
    /// 是否处于超级护甲状态
    /// </summary>
    public bool IsSuperArmor { get; private set; }

    /// <summary>
    /// 移动组件 - 安全访问
    /// </summary>
    public MoveComponent MoveComponent
    {
        get
        {
            return GetEntityComponent<MoveComponent>();
        }
    }

    /// <summary>
    /// 生命组件 - 安全访问
    /// </summary>
    public HealthComponent HealthComponent
    {
        get
        {
            return GetEntityComponent<HealthComponent>();
        }
    }

    /// <summary>
    /// 属性组件 - 安全访问
    /// </summary>
    public AttrComponent AttrComponent
    {
        get
        {
            return GetEntityComponent<AttrComponent>();
        }
    }

    /// <summary>
    /// 攻击组件 - 安全访问
    /// </summary>
    public AttackComponent AttackComponent
    {
        get
        {
            return GetEntityComponent<AttackComponent>();
        }
    }

    /// <summary>
    /// Buff组件 - 安全访问
    /// </summary>
    public BuffComponent BuffComponent
    {
        get
        {
            return GetEntityComponent<BuffComponent>();
        }
    }

    /// <summary>
    /// 状态机组件 - 安全访问
    /// </summary>
    public FSMComponent FSMComponent
    {
        get
        {
            return GetEntityComponent<FSMComponent>();
        }
    }

    /// <summary>
    /// 技能攻击指示器组件 - 安全访问
    /// </summary>
    public SkillAttackIndicators SkillAttackIndicators
    {
        get
        {
            return GetEntityComponent<SkillAttackIndicators>();
        }
    }

    protected virtual void Awake()
    {
        this.Initialize();
        // 自动注册到 EntityService
        RegisterToEntityService();
    }

    /// <summary>
    /// 注册到 EntityService
    /// </summary>
    private void RegisterToEntityService()
    {
        // 延迟注册，确保 ServiceManager 已经初始化
        StartCoroutine(DelayedRegister());
    }

    private System.Collections.IEnumerator DelayedRegister()
    {
        // 等待最多 10 帧，确保 ServiceManager 已经初始化
        int maxAttempts = 10;
        int attempts = 0;
        
        while (attempts < maxAttempts)
        {
            yield return null;
            attempts++;
            
            var entityService = ServiceManager.Instance?.GetService<EntityService>();
            if (entityService != null)
            {
                entityService.RegisterEntity(this);
                yield break; // 注册成功，退出协程
            }
        }
        
        // 如果多次尝试后仍然失败，记录警告
        Logger.LogWarning("Entity", $"EntityService not found after {maxAttempts} attempts when trying to register {name}");
    }

    /// <summary>
    /// 获取组件 - 支持可选组件，按需获取
    /// </summary>
    public T GetEntityComponent<T>() where T : Component
    {
        var type = typeof(T);
        
        if (m_ComponentCache.TryGetValue(type, out var cachedComponent))
        {
            return cachedComponent as T;
        }
        
        var component = GetComponent<T>();
        if (component != null)
        {
            m_ComponentCache[type] = component;
        }
        
        return component;
    }

    /// <summary>
    /// 检查是否有指定组件
    /// </summary>
    public bool HasComponent<T>() where T : Component
    {
        return GetEntityComponent<T>() != null;
    }

    public virtual void Initialize()
    {
        // 获取Animator（大部分实体都需要）
        this.Animator = GetComponentInChildren<Animator>();

        // 按需初始化组件，不强求所有组件都存在
        
        // 生命值组件 - 大部分实体都需要
        var healthComponent = GetEntityComponent<HealthComponent>();
        if (healthComponent != null)
        {
            healthComponent.Initialize(EntityData.Health);
        }
        
        // 属性组件 - 大部分实体都需要
        var attrComponent = GetEntityComponent<AttrComponent>();
        if (attrComponent != null)
        {
            attrComponent.Initialize();
        }
        
        // 移动组件 - 只有需要移动的实体才有
        var moveComponent = GetEntityComponent<MoveComponent>();
        if (moveComponent != null)
        {
            moveComponent.Initialize(EntityData.Speed);
        }
        
        // 攻击组件 - 只有需要攻击的实体才有
        var attackComponent = GetEntityComponent<AttackComponent>();
        if (attackComponent != null)
        {
            attackComponent.Initialize(EntityData.AttackData);
        }
        
        // 状态机组件 - 只有需要复杂状态管理的实体才有
        var fsmComponent = GetEntityComponent<FSMComponent>();
        if (fsmComponent != null)
        {
            fsmComponent.Initialize();
        }
        
        // Buff组件 - 只有需要Buff系统的实体才有
        var buffComponent = GetEntityComponent<BuffComponent>();
        if (buffComponent != null)
        {
            // Buff组件初始化逻辑
        }
        
        // 技能指示器 - 只有需要技能显示的实体才有
        var skillIndicators = GetEntityComponent<SkillAttackIndicators>();
        if (skillIndicators != null)
        {
            // 从 EntityData.AttackData.IndicatorData 读取指示器数据
            IndicatorData indicatorData = null;
            if (EntityData != null && EntityData.AttackData != null)
            {
                indicatorData = EntityData.AttackData.IndicatorData;
            }
            skillIndicators.Initialize(indicatorData);
        }
    }

    /// <summary>
    /// 设置隐身状态
    /// </summary>
    /// <param name="stealth">是否隐身</param>
    public void SetStealth(bool stealth)
    {
        IsStealth = stealth;
    }

    /// <summary>
    /// 设置超级护甲状态
    /// </summary>
    /// <param name="superArmor">是否超级护甲</param>
    public void SetSuperArmor(bool superArmor)
    {
        IsSuperArmor = superArmor;
    }

    private void OnTriggerEnter2D(Collider2D collision)
    {
        //Logger.Log("Entity", $"OnTriggerEnter2D 实体==>>> self:{gameObject.name} find : {collision.gameObject.name}");
        
        // 检查碰撞的对象是否是实体
        var otherEntity = collision.GetComponent<Entity>();
        if (otherEntity == null) return;
        
        // 检查是否是敌人关系
        bool isEnemy = false;
        // 土豆地雷不应该被僵尸攻击，也不应该吸引僵尸的仇恨
        if (this is Zombie && otherEntity is Plant && !(otherEntity is PotatoMine))
        {
            isEnemy = true;
        }
        else if (this is Plant && otherEntity is Zombie && !(this is PotatoMine))
        {
            isEnemy = true;
        }
        
        // 如果是敌人，且当前实体是僵尸，则切换到攻击状态
        if (isEnemy && this is Zombie zombie)
        {
            // 检查是否有FSM组件和AttackComponent
            if (zombie.FSMComponent != null && zombie.AttackComponent != null)
            {
                // 检查当前状态是否是移动状态或空闲状态
                var currentState = zombie.FSMComponent.State;
                if (currentState == FSMType.Move || currentState == FSMType.Idle)
                {
                    Logger.Log("Entity", $"{zombie.name} 检测到敌人 {otherEntity.name}，切换到攻击状态");
                    zombie.FSMComponent.ChangeStatus(FSMType.Attack, otherEntity);
                }
            }
        }
    }

    /// <summary>
    /// 设置实体颜色（虚方法，子类实现）
    /// </summary>
    /// <param name="color">目标颜色</param>
    /// <param name="duration">颜色变化持续时间（秒），之后自动恢复原色</param>
    public virtual void SetColor(Color color, float duration = 0.1f)
    {
        // 默认实现为空，由子类实现
    }

    /// <summary>
    /// 实体销毁时注销
    /// </summary>
    protected virtual void OnDestroy()
    {
        // 从 EntityService 注销
        var entityService = ServiceManager.Instance?.GetService<EntityService>();
        if (entityService != null)
        {
            entityService.UnregisterEntity(this);
        }
    }
}